<template>
  <div class="unit-converter-tool">
    <div class="tool-header">
      <h1>单位转换器</h1>
      <p>长度、重量、温度等单位转换工具</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 转换器主体 -->
        <el-col :span="16">
          <div class="converter-section">
            <div class="converter-header">
              <h3>单位转换</h3>
              <el-select v-model="selectedCategory" @change="onCategoryChange" size="large">
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>
            </div>
            
            <div class="converter-body">
              <div class="input-group">
                <div class="input-label">从</div>
                <div class="input-container">
                  <el-input-number
                    v-model="inputValue"
                    :precision="6"
                    :step="0.1"
                    size="large"
                    placeholder="输入数值"
                    @change="convert"
                  />
                  <el-select v-model="fromUnit" @change="convert" size="large">
                    <el-option
                      v-for="unit in currentUnits"
                      :key="unit.value"
                      :label="unit.label"
                      :value="unit.value"
                    />
                  </el-select>
                </div>
              </div>
              
              <div class="conversion-arrow">
                <el-icon :size="24"><Switch /></el-icon>
                <el-button @click="swapUnits" type="primary" circle>
                  <el-icon><Refresh /></el-icon>
                </el-button>
              </div>
              
              <div class="output-group">
                <div class="output-label">到</div>
                <div class="output-container">
                  <el-input-number
                    v-model="outputValue"
                    :precision="6"
                    :step="0.1"
                    size="large"
                    readonly
                    placeholder="转换结果"
                  />
                  <el-select v-model="toUnit" @change="convert" size="large">
                    <el-option
                      v-for="unit in currentUnits"
                      :key="unit.value"
                      :label="unit.label"
                      :value="unit.value"
                    />
                  </el-select>
                </div>
              </div>
            </div>
            
            <!-- 快速转换结果 -->
            <div class="quick-results" v-if="quickResults.length > 0">
              <h4>常用单位转换</h4>
              <div class="results-grid">
                <div 
                  v-for="result in quickResults" 
                  :key="result.unit"
                  class="result-item"
                  @click="selectQuickResult(result)"
                >
                  <div class="result-value">{{ result.value }}</div>
                  <div class="result-unit">{{ result.label }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 转换历史和说明 -->
        <el-col :span="8">
          <div class="history-section">
            <div class="section-header">
              <h3>转换历史</h3>
              <el-button @click="clearHistory" size="small" type="danger">清空</el-button>
            </div>
            
            <div class="history-list">
              <div 
                v-for="(item, index) in history" 
                :key="index"
                class="history-item"
                @click="loadFromHistory(item)"
              >
                <div class="history-conversion">
                  {{ item.inputValue }} {{ item.fromUnit }} = {{ item.outputValue }} {{ item.toUnit }}
                </div>
                <div class="history-category">{{ item.category }}</div>
              </div>
              <div v-if="history.length === 0" class="empty-history">
                暂无转换历史
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>支持的单位类型：</h4>
                <ul>
                  <li><strong>长度：</strong> 米、千米、厘米、毫米、英寸、英尺、码、英里</li>
                  <li><strong>重量：</strong> 克、千克、磅、盎司、吨、毫克</li>
                  <li><strong>温度：</strong> 摄氏度、华氏度、开尔文</li>
                  <li><strong>面积：</strong> 平方米、平方千米、公顷、平方英尺、平方英寸</li>
                  <li><strong>体积：</strong> 升、毫升、立方米、加仑、品脱、夸脱</li>
                  <li><strong>时间：</strong> 秒、分钟、小时、天、周、月、年</li>
                </ul>
                
                <h4>使用方法：</h4>
                <ol>
                  <li>选择要转换的单位类型</li>
                  <li>输入要转换的数值</li>
                  <li>选择源单位和目标单位</li>
                  <li>查看转换结果</li>
                </ol>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 温度转换需要考虑不同的基准点</p>
                  <p>⚠️ 某些单位转换可能存在精度误差</p>
                  <p>⚠️ 建议使用科学计数法处理极大或极小数值</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Switch, Refresh } from '@element-plus/icons-vue'

const selectedCategory = ref('length')
const inputValue = ref(1)
const outputValue = ref(0)
const fromUnit = ref('')
const toUnit = ref('')
const history = ref([])

const categories = [
  { value: 'length', label: '长度' },
  { value: 'weight', label: '重量' },
  { value: 'temperature', label: '温度' },
  { value: 'area', label: '面积' },
  { value: 'volume', label: '体积' },
  { value: 'time', label: '时间' }
]

const units = {
  length: [
    { value: 'mm', label: '毫米 (mm)', factor: 0.001 },
    { value: 'cm', label: '厘米 (cm)', factor: 0.01 },
    { value: 'm', label: '米 (m)', factor: 1 },
    { value: 'km', label: '千米 (km)', factor: 1000 },
    { value: 'in', label: '英寸 (in)', factor: 0.0254 },
    { value: 'ft', label: '英尺 (ft)', factor: 0.3048 },
    { value: 'yd', label: '码 (yd)', factor: 0.9144 },
    { value: 'mi', label: '英里 (mi)', factor: 1609.344 }
  ],
  weight: [
    { value: 'mg', label: '毫克 (mg)', factor: 0.000001 },
    { value: 'g', label: '克 (g)', factor: 0.001 },
    { value: 'kg', label: '千克 (kg)', factor: 1 },
    { value: 't', label: '吨 (t)', factor: 1000 },
    { value: 'oz', label: '盎司 (oz)', factor: 0.0283495 },
    { value: 'lb', label: '磅 (lb)', factor: 0.453592 }
  ],
  temperature: [
    { value: 'c', label: '摄氏度 (°C)', factor: 1, offset: 0 },
    { value: 'f', label: '华氏度 (°F)', factor: 5/9, offset: -32 },
    { value: 'k', label: '开尔文 (K)', factor: 1, offset: 273.15 }
  ],
  area: [
    { value: 'mm2', label: '平方毫米 (mm²)', factor: 0.000001 },
    { value: 'cm2', label: '平方厘米 (cm²)', factor: 0.0001 },
    { value: 'm2', label: '平方米 (m²)', factor: 1 },
    { value: 'km2', label: '平方千米 (km²)', factor: 1000000 },
    { value: 'ha', label: '公顷 (ha)', factor: 10000 },
    { value: 'in2', label: '平方英寸 (in²)', factor: 0.00064516 },
    { value: 'ft2', label: '平方英尺 (ft²)', factor: 0.092903 }
  ],
  volume: [
    { value: 'ml', label: '毫升 (ml)', factor: 0.001 },
    { value: 'l', label: '升 (l)', factor: 1 },
    { value: 'm3', label: '立方米 (m³)', factor: 1000 },
    { value: 'gal', label: '加仑 (gal)', factor: 3.78541 },
    { value: 'pt', label: '品脱 (pt)', factor: 0.473176 },
    { value: 'qt', label: '夸脱 (qt)', factor: 0.946353 }
  ],
  time: [
    { value: 's', label: '秒 (s)', factor: 1 },
    { value: 'min', label: '分钟 (min)', factor: 60 },
    { value: 'h', label: '小时 (h)', factor: 3600 },
    { value: 'd', label: '天 (d)', factor: 86400 },
    { value: 'w', label: '周 (w)', factor: 604800 },
    { value: 'month', label: '月 (month)', factor: 2629746 },
    { value: 'y', label: '年 (y)', factor: 31556952 }
  ]
}

const currentUnits = computed(() => {
  return units[selectedCategory.value] || []
})

const quickResults = computed(() => {
  if (!fromUnit.value || !toUnit.value || !inputValue.value) return []
  
  const results = []
  const currentUnitList = currentUnits.value
  
  // 显示其他常用单位的转换结果
  currentUnitList.forEach(unit => {
    if (unit.value !== fromUnit.value && unit.value !== toUnit.value) {
      const convertedValue = convertValue(inputValue.value, fromUnit.value, unit.value)
      results.push({
        unit: unit.value,
        label: unit.label,
        value: formatNumber(convertedValue)
      })
    }
  })
  
  return results.slice(0, 6) // 最多显示6个
})

const onCategoryChange = () => {
  const unitList = currentUnits.value
  if (unitList.length > 0) {
    fromUnit.value = unitList[0].value
    toUnit.value = unitList[1]?.value || unitList[0].value
    convert()
  }
}

const convert = () => {
  if (!fromUnit.value || !toUnit.value || inputValue.value === null) return
  
  const result = convertValue(inputValue.value, fromUnit.value, toUnit.value)
  outputValue.value = result
  
  // 添加到历史
  addToHistory()
}

const convertValue = (value, from, to) => {
  if (selectedCategory.value === 'temperature') {
    return convertTemperature(value, from, to)
  }
  
  const fromUnitData = currentUnits.value.find(u => u.value === from)
  const toUnitData = currentUnits.value.find(u => u.value === to)
  
  if (!fromUnitData || !toUnitData) return 0
  
  // 先转换为基准单位，再转换为目标单位
  const baseValue = value * fromUnitData.factor
  return baseValue / toUnitData.factor
}

const convertTemperature = (value, from, to) => {
  // 先转换为摄氏度
  let celsius
  switch (from) {
    case 'c':
      celsius = value
      break
    case 'f':
      celsius = (value - 32) * 5 / 9
      break
    case 'k':
      celsius = value - 273.15
      break
    default:
      celsius = value
  }
  
  // 再从摄氏度转换为目标单位
  switch (to) {
    case 'c':
      return celsius
    case 'f':
      return celsius * 9 / 5 + 32
    case 'k':
      return celsius + 273.15
    default:
      return celsius
  }
}

const formatNumber = (num) => {
  if (Math.abs(num) < 0.000001) return '0'
  if (Math.abs(num) > 1000000) {
    return num.toExponential(6)
  }
  return parseFloat(num.toFixed(6)).toString()
}

const swapUnits = () => {
  const temp = fromUnit.value
  fromUnit.value = toUnit.value
  toUnit.value = temp
  convert()
}

const selectQuickResult = (result) => {
  toUnit.value = result.unit
  convert()
}

const addToHistory = () => {
  const categoryLabel = categories.find(c => c.value === selectedCategory.value)?.label || ''
  
  history.value.unshift({
    inputValue: inputValue.value,
    outputValue: formatNumber(outputValue.value),
    fromUnit: fromUnit.value,
    toUnit: toUnit.value,
    category: categoryLabel
  })
  
  // 限制历史记录数量
  if (history.value.length > 50) {
    history.value = history.value.slice(0, 50)
  }
}

const loadFromHistory = (item) => {
  inputValue.value = item.inputValue
  fromUnit.value = item.fromUnit
  toUnit.value = item.toUnit
  convert()
}

const clearHistory = () => {
  history.value = []
  ElMessage.success('历史记录已清空')
}

onMounted(() => {
  onCategoryChange()
})
</script>

<style scoped>
.unit-converter-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.converter-section,
.history-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.converter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.converter-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.converter-body {
  margin-bottom: 30px;
}

.input-group,
.output-group {
  margin-bottom: 20px;
}

.input-label,
.output-label {
  font-weight: 500;
  color: #666;
  margin-bottom: 8px;
  font-size: 1rem;
}

.input-container,
.output-container {
  display: flex;
  gap: 12px;
}

.input-container .el-input-number,
.output-container .el-input-number {
  flex: 1;
}

.input-container .el-select,
.output-container .el-select {
  flex: 1;
}

.conversion-arrow {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
  gap: 15px;
}

.conversion-arrow .el-icon {
  color: #667eea;
}

.quick-results {
  margin-top: 30px;
}

.quick-results h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
}

.result-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.result-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.result-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.result-unit {
  font-size: 0.9rem;
  color: #666;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  background: #f8f9fa;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-conversion {
  font-size: 1rem;
  color: #333;
  margin-bottom: 4px;
}

.history-category {
  font-size: 0.8rem;
  color: #666;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul,
.help-content ol {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .converter-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .input-container,
  .output-container {
    flex-direction: column;
  }
  
  .results-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .history-item {
    padding: 8px;
  }
}
</style>
